# 导入CSV模块
import csv
# 导入tushare
import tushare as ts
import time
import threading
import time
import sys
import threading
import simTrade
from datetime import datetime
import os


def thread_func():  # 线程函数
    print('我是一个线程函数', datetime.now())


def many_thread():
    threads = []
    for _ in range(10):  # 循环创建10个线程
        t = threading.Thread(target=thread_func)
        threads.append(t)
    for t in threads:  # 循环启动10个线程
        t.start()


def progress_bar(i):
    print("\r", end="")    # 输出位置回到行首
    # 显示进度百分比，并同时显示进度1/2(可以自己调节)个数的进度条符号：▋
    print("处理进度：{}%:".format(i), "▋" * (i//10), end="")
    print(f'耗时:{time.time() - t:.8f}s', end="")  # 时间统计结束
    sys.stdout.flush()


def read_base_fun():
    # 初始化pro接口
    pro = ts.pro_api(
        '226fb55054b34f283ce9efef0f35b937bd0fb60d3d91b446f35236a8')

    # 拉取数据
    da = pro.stock_basic(**{
        "ts_code": "",
        "name": "",
        "exchange": "",
        "market": "",
        "is_hs": "",
        "list_status": "",
        "limit": "",
        "offset": ""
    }, fields=[
        "ts_code",
        "symbol",  # 股票代码
        "name",  # 股票名称
        "area",  # 地域
        "industry",  # 所属行业
        "market",  # 市场类型
        "list_date",  # 上市日期
        "delist_date",  # 退市日期
        "fullname",  # 股票全称
        "list_status",  # 上市状态 L上市 D退市 P暂停上市
        "exchange"  # 交易所 SSE上交所 SZSE深交所 HKEX港交所
    ])
    return da, pro


def history_fun(pro, ts_code, start_date, end_date, name):
    # 拉取数据
    db = pro.daily(**{
        "ts_code": ts_code,
        "trade_date": "",
        "start_date": start_date,
        "end_date": end_date,
        "offset": "",
        "limit": ""
    }, fields=[
        "ts_code",
        "trade_date",
        "open",
        "high",
        "low",
        "close",
        "pre_close",
        "change",
        "pct_chg",
        "vol",
        "amount"
    ])
    # db.to_csv(name.replace("*", "")+'.csv')


def write_header():
    with open('模拟交易结果统计.csv', 'a', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=[
                                '持股时间', '股票代码', '所属行业', '所属板块', '股票简称', '换手次数（元）', '原股票涨跌幅（%）', '最终余额', '最后一次交易股票价格', '盈利百分比（%）'])
        writer.writeheader()


def save_data(dic):
    with open('模拟交易结果统计.csv', 'a', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=[
                                '持股时间', '股票代码', '所属行业', '所属板块', '股票简称', '换手次数（元）', '原股票涨跌幅（%）', '最终余额（万）', '最后一次交易股票价格', '盈利百分比（%）'])
        writer.writerow(dic)


def main():
    if (os.path.isfile('stock_lists.csv')):
        os.remove('stock_lists.csv')
    if (os.path.isfile('模拟交易结果统计.csv')):
        os.remove('模拟交易结果统计.csv')
    yuan_money = 100  # 单位万
    da, pro = read_base_fun()

    da.to_csv('stock_lists.csv')
    read_header = False
    write_header()

    total = len(open("stock_lists.csv", "r", encoding='utf-8').readlines())
    dic = {}
    with open("stock_lists.csv", "r", encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            i = reader.line_num

            progress_bar(int(i*100/total))
            if read_header == True:
                # t = threading.Thread(target=history_fun(pro,row[1],"20180101","20230117",row[1]+"_"+row[3]))
                # t.start()
                date, num, price_rate, end_sell_price = simTrade.sim_trade(
                    yuan_money, row[1], pro, 0, 1)
                dic['持股时间'] = 000
                dic['股票代码'] = row[1]
                dic['股票简称'] = row[3]
                dic['所属行业'] = row[5]
                dic['所属板块'] = row[7]
                dic['换手次数（元）'] = num
                dic['原股票涨跌幅（%）'] = price_rate
                dic['最终余额（万）'] = round(date/10000, 3)
                dic['盈利百分比（%）'] = round((date - yuan_money*10000)/10000, 3)
                dic['最后一次交易股票价格'] = end_sell_price

                print(row[1]+"_"+row[3], "本金100万,余额=",
                      round(date/10000, 3), "换手次数=", num)
                # history_fun(pro, row[1], "20180101",
                # "20230117", row[1]+"_"+row[3])
                save_data(dic)
            read_header = True


if __name__ == '__main__':
    t = time.time()
    print("时间统计开始")  # 时间统计开始
    main()
